package com.appspot.smartgan;

import com.appspot.smartgan.server.Client;
import com.appspot.smartgan.server.HttpClient;
import com.appspot.smartgan.server.UrlGenerator;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;

/**
 * The handles a broadcast received from the GCM
 * and tells the application that GcmIntentSerrvice is going to handle
 * the new incoming message.
 * @author Dor Mesica
 */
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

	public static final String REGISTRATION_ID = "GCMBroadcastReceiver.REGISTRATION_ID";

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.i("SMARTGAN", "notification received");

		SharedPreferences prefs = context.getSharedPreferences
				(MainActivity.SHARED_PREFERENCES, Context.MODE_PRIVATE);

		String regid = intent.getExtras().getString("registration_id");
		if (regid != null && !regid.equals("") && 
				intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
			sendRegistrationIdToServer(context, regid);

			// save registration id to SharedPreferences
			SharedPreferences.Editor editor = prefs.edit();
			editor.putString(MainActivity.PROPERTY_REG_ID, regid);
			editor.commit();
		}

		// get registration id from shared prefs
		// "" should never be returned
		regid = prefs.getString(MainActivity.PROPERTY_REG_ID, "");
		intent.putExtra(REGISTRATION_ID, regid);

		// Explicitly specify that GcmIntentService will handle the intent.
		ComponentName comp = new ComponentName(context.getPackageName(),
				GcmIntentService.class.getName());

		// Start the service, keeping the device awake while it is launching.
		startWakefulService(context, (intent.setComponent(comp)));

		setResultCode(Activity.RESULT_OK);
	}

	/*
	 * sends the registration id to the server
	 * so it could store it and associate it with the
	 * parent id that will be sent in the same URL
	 */
	private void sendRegistrationIdToServer(Context context, String regid) {
		SharedPreferences prefs = context.getSharedPreferences
				(MainActivity.SHARED_PREFERENCES, Context.MODE_PRIVATE);
		String parentId = prefs.getString(MainActivity.PARENT_ID, "");
		
		Log.v("SMARTGAN", "parent id: " + parentId);
		String url = UrlGenerator.registrationId(regid, parentId);

		Client client = new HttpClient(url, Client.RESPONSE_BOOLEAN);
		client.execute();
	}
	
}
